package businessServlets;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import validate.Validate;

import com.google.appengine.api.datastore.Email;
import com.google.appengine.api.datastore.PhoneNumber;
import com.tecnick.htmlutils.htmlentities.HTMLEntities;

import controller.Controller;

@SuppressWarnings("serial")
public class ChangePropertiesBusiness extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		System.out.println(isMultipart);
		
		
		/*if (!isMultipart)
		{			
			System.out.println("not multipart - not supposed to be here..");			
		}
		else
		{*/
			try { 
				
				HashMap<String, String> formFields = new HashMap<String, String>();
				
				System.out.println("multi");
				ServletFileUpload upload = new ServletFileUpload();       
				//resp.setContentType("text/plain");
				
				FileItemIterator iterator = upload.getItemIterator(req); 
				
				String name;
				String value;
				byte[] imageBytes = null;
				boolean ie = false;

				while (iterator.hasNext()) {         
					FileItemStream item = iterator.next(); 
					InputStream stream = item.openStream();
				
					//string field
					if (item.isFormField()) {
						name = item.getFieldName();
						if(ie)
							value = getParameter(Streams.asString(stream,"UTF-8"),ie);
						else
							value = Streams.asString(stream);
						if(!ie && name.equals("brows") && value.equals("ie"))
							ie=true;						System.out.println("form field " + name + " value: "+value);
						formFields.put(name, value);
												
					}
					else //image
					{
						
						try
						{
							int len;           
							imageBytes = IOUtils.toByteArray(stream);
							
							if (imageBytes.length==0)
							{
								System.out.println("size 0 -> no image");
								imageBytes = null;
							}
							else
							{
								System.out.println("there is an image");
							}
							
							
							//resp.getOutputStream().write(newImage.getImageData(), 0, newImage.getImageData().length);
						}catch(Exception e)
						{
							e.printStackTrace();
							System.out.println("no image");
						}
						
						
					}
				} //end while
				
				
				String userName = (String) req.getSession().getAttribute("userNameBusiness");
				String password = formFields.get("password");
				String password1 = formFields.get("password1");
				Email email = new Email(formFields.get("email"));
				String businessName = formFields.get("businessName");
				String bizType = formFields.get("bizTypeSelect");
				String businessNumber = formFields.get("businessNumber");
				PhoneNumber phone = new PhoneNumber(formFields.get("phone"));
				String background = formFields.get("background");
				String secBackground = formFields.get("secBackground");
				String borderColor = formFields.get("borderColor");
				String website = formFields.get("site");
				String skype = formFields.get("skype");
				Long[] orderUrgencyTime = new Long[3];
				try{
					orderUrgencyTime[0] = Math.max(0,((Long.parseLong(formFields.get("days0"))*24+Long.parseLong(formFields.get("hours0")))*60+Long.parseLong(formFields.get("minutes0")))*60000);
					orderUrgencyTime[1] = Math.max(0,((Long.parseLong(formFields.get("days1"))*24+Long.parseLong(formFields.get("hours1")))*60+Long.parseLong(formFields.get("minutes1")))*60000);
					orderUrgencyTime[2] = Math.max(0,((Long.parseLong(formFields.get("days2"))*24+Long.parseLong(formFields.get("hours2")))*60+Long.parseLong(formFields.get("minutes2")))*60000);
				}
				catch(Exception ex){
					orderUrgencyTime = null;
				}
				System.out.println("!!!!!!!"+userName + " " + password + " " + password1 + " "+ email.getEmail() + " "+ businessName + " "+  businessNumber +" " + phone.getNumber());
				
				ArrayList<String> status = new ArrayList<String>();
				int i=0;
				
				while (formFields.get("list_"+i)!=null)
				{
					System.out.println("list_"+formFields.get("list_"+i));
					status.add(new String(formFields.get("list_"+i).substring(5).replaceAll("@", " ")));
					i++;
				}
				
				ArrayList<String> message = new ArrayList<String>();
				i=0;
				
				while (formFields.get("message_"+i)!=null)
				{
					System.out.println("message_"+formFields.get("message_"+i));
					message.add(new String(formFields.get("message_"+i).substring(5).replaceAll("@", " ")));
					i++;
				}
				
				String validString =Validate.checkBizValid(businessName, businessNumber, imageBytes, phone, email, userName, password,password1, status, null, message);
				
				if (validString.equals(""))
				{
					PhoneNumber newPhone = new PhoneNumber(phone.getNumber().replaceAll("-", ""));
					//Long[] orderUrgencyTime = {1000L,2000L,3000L};
					int result = Controller.getInstance().updateBisAccount(businessName,bizType, businessNumber, imageBytes, newPhone, email, website, userName, password, status, null, message,
							background, secBackground,  borderColor,skype,orderUrgencyTime);
										
					switch (result)
					{
					case 0:
						req.getSession().removeAttribute("validErrorBiz");
						resp.sendRedirect("allOrders.jsp");
						break;
					case 1:
						req.getSession().setAttribute("validErrorBiz","username not exists");
						resp.sendRedirect("home.jsp#joinbiz");
						break;
					case 2:
						req.getSession().setAttribute("validErrorBiz","business name already exists");
						resp.sendRedirect("home.jsp#joinbiz");
						break;						
					}
					
				}
				else
				{
					req.getSession().setAttribute("validErrorBiz",validString);
					resp.sendRedirect("home.jsp#joinbiz");
				}
												

			} catch (Exception ex) {
				throw new ServletException(ex);     
			}
			
//		}
		System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		

	}
	
	private String getParameter(String param,boolean ie){
		if(ie){
			return HTMLEntities.htmlentities(param);
		}
		return param;
	}
	
}



//if (!isMultipart)
//{
//	String userName = (String) req.getSession().getAttribute("userNameBusiness");
//	//String userName = req.getParameter("userName"); //not change
//	//req.getSession().setAttribute("userNameBusiness", userName);
//	String password = req.getParameter("password");
//	String password1 = req.getParameter("password1");
//	Email email = new Email(req.getParameter("email"));
//	String businessName = req.getParameter("businessName");
//	String businessNumber = req.getParameter("businessNumber");
//	PhoneNumber phone = new PhoneNumber(req.getParameter("phone"));
//	
//	
//	System.out.println("change to "+ password + " " + password1 + " "+ email.getEmail() + " "+ businessName + " "+  businessNumber +" " + phone.getNumber());
//	
//	ArrayList<String> status = new ArrayList<String>();
//	int i=1;
//	
//	while (req.getParameter("statusItem"+i)!=null)
//	{
//		System.out.println("statusItem"+req.getParameter("statusItem"+i));
//		status.add(req.getParameter("statusItem"+i));
//		i++;
//	}
//	
//	ArrayList<String> message = new ArrayList<String>();
//	i=1;
//	
//	while (req.getParameter("messageItem"+i)!=null)
//	{
//		System.out.println("messageItem"+req.getParameter("messageItem"+i));
//		message.add(req.getParameter("messageItem"+i));
//		i++;
//	}
//	
//	Controller.getInstance().updateBisAccount(businessName, businessNumber, null, phone, email, userName, password, status, null, message);
//	//addOrder.jsp
//	//System.out.println(req.getParameter("logo"));
//	
//	
//	//resp.getWriter().println(req.getParameter("userName")+", welcome! =)");
//	
//}